package com.zhongan.cloud.config.demo;

import java.lang.reflect.Field;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

/**
 * 代理目标对象工具类
 * @author chengkai
 *
 */
public class ProxyTargetUtils {

    public static boolean isCglibProxy(Object proxy) {
        return AopUtils.isCglibProxy(proxy);
    }

    public static boolean isJdkDynamicProxy(Object proxy) {
        return AopUtils.isJdkDynamicProxy(proxy);
    }

    public static Object getTarget(Object proxy) {
        if (AopUtils.isCglibProxy(proxy)) {
            return getCglibProxyTargetObject(proxy);
        } else if (AopUtils.isJdkDynamicProxy(proxy)) {
            return getJdkDynamicProxyTargetObject(proxy);
        } else {
            return proxy;
        }
    }

    private static Object getCglibProxyTargetObject(Object proxy) {
        Object target = null;
        try {
            Field field = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
            field.setAccessible(true);
            Object dynamicAdvisedInterceptor = field.get(proxy);

            Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
            advised.setAccessible(true);

            target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return target;
    }

    private static Object getJdkDynamicProxyTargetObject(Object proxy) {
        Object target = null;
        try {
            Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
            h.setAccessible(true);
            AopProxy aopProxy = (AopProxy) h.get(proxy);

            Field advised = aopProxy.getClass().getDeclaredField("advised");
            advised.setAccessible(true);

            target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return target;
    }

}
